import auConfig from "../auConfig"
import IP from 'ip'
import {ipcMain} from "electron"
import imageHelper from "./imageHelper"
const uuid=require('uuid');
const EventEmitter = require('events').EventEmitter;
const WssEmitter = new EventEmitter();
const fs = require('fs');
const path = require('path');
const os = require('os');
const { app, protocol } = require('electron')



// 导入WebSocket模块:
const WebSocket = require('ws');

let wss = null;
//ip、phoneName、
let wsList={};

//获取客户端列表
function getClients(){
    let list=[];
    Object.keys(wsList).forEach((key)=>{
        list.push({
            ip:key,
            phoneName:wsList[key].phoneName,
        });
    })
    return list;
}

//初始化wss
ipcMain.handle('wss-init', (event, someArgument) => {
    //如果wss
    if(!wss){
        wsInit();
    }
    let ip=IP.address();
    if(ip){
        ip=ip+":"+auConfig.socket.port;
    }
    return {
        ip:ip,
        clients:getClients()
    };
})

//获取客户端列表
ipcMain.handle('wss-client',(event, someArgument) => {
    return getClients();
})

//重启服务
ipcMain.handle('wss-reload',(event, someArgument) => {
    if(wss){
        wss.close();
        wss=null;
    }
    wsList={};
    wsInit();
    return true;
})

//发送
ipcMain.handle('wss-send',(event, someArgument) => {
    if(!someArgument.ip || !wsList[someArgument.ip]){
        return false;
    }
    return wsSend(someArgument.code,null,wsList[someArgument.ip].ws);
})
var filePath=null;
//发送等待返回
ipcMain.handle('wss-send-wait',(event, someArgument) => {
    if(!someArgument.ip || !wsList[someArgument.ip]){
        return false;
    }
    let id=uuid.v4();
    console.log(id);

    return new Promise((resolve, reject) => {
        wsSend(someArgument.code,{id},wsList[someArgument.ip].ws);
        WssEmitter.once(id,function(info){
            //创建临时目录
            if(info.code==202){
                imageHelper.createdFile(Buffer.from(info.image, 'base64')).then(info=>resolve(info))
            }
        });
    });
})

/*
200正常
201已经有另一个连接了
202截屏
 */
function wsSend(code,info,ws){
    if(!info){
        info={};
    }
    if(typeof info!="object"){
        info={
            info
        };
    }
    return ws.send(JSON.stringify({
        code,
        ...info
    }));
}

function addClient(ws,req){
    const ip = req.connection.remoteAddress.match(/((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)/)[0];
    if(wsList[ip]){
        wsSend(201,"已经有另一个连接了",ws);
        ws.close();
        return ip;
    }
    wsList[ip]={ws,req};
    console.log("连接成功："+ip);

    return ip;
}

function wsInit(){
    if(!wss){
        wss = new WebSocket.Server(auConfig.socket)
    }
    wss.on('connection', function (ws,req) {

        let ip=addClient(ws,req);

        ws.on('message', function (message) {
            let info=JSON.parse(message);
            if(info.id){
                WssEmitter.emit(info.id,info);
            }
        });
        ws.on("close",function (){
            console.log("关闭了连接：",ip);
            wsList[ip] && delete wsList[ip];
        })
        ws.on("error",function(e){
            console.log(e);
            console.log("错误：",ip);
        })
        // let timer=setInterval(()=>{
        //     wsSend(0,"0",ws);
        // },1000)
    });
}
